<?php

namespace App\Http\Controllers\Shop;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Http\Resources\Shop\Product as OrderResource;
use App\Http\Resources\Shop\ProductCollection;
use App\Handlers\ImageUploadHandler;
use App\Models\Product;
use Validator;
use Auth;

class ProductController extends ApiController
{
    /**
     * 商品列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $limit = $request->input('size', 15);
        $status = $request->input('status');
        $keyWord = $request->input('keyword');

        $productOrm = Product::where('shop_id', $request->user('shop')->id);

        if (is_numeric($status) && in_array($status, [0, 1])) {
            $productOrm->where('status', $status);
        }
        
        if ($keyWord) {
            $productOrm->where('name', 'LIKE', "%{$keyWord}%");
        }

        $productOrm->orderBy('created_at', 'DESC');

        return new ProductCollection($productOrm->paginate($limit));
    }


    /**
     * 新增.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $messages = [
            'name.required' => '商品名称不能为空',
            'cover_image.required' => '商品封面不能为空',
            'price.required' => '商品价格不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'cover_image' => 'required',
            'price' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $picGroup = $request->input('pic_group', []);

        // 处理商品封面图片
        $coverImage = $request->input('cover_image', '');
        if(!$coverImage){
            // 没有上传封面图片的时候从图片组里面获取第一张做封面图片
            $coverImage = $picGroup ? $picGroup[0] : '';
        }

        $product = new Product();
        $product->shop_id = $request->user('shop')->id; // 店铺ID
        $product->name = $request->input('name');
        $product->price = number_format($request->input('price'), 2, '.', '');
        $product->unit = $request->input('unit');
        $product->info = $request->input('info');
        $product->description = $request->input('desc');
        $product->cover_image = $coverImage;
        $product->pic_group = $picGroup; // 图片组存为json格式数据
        $product->spec = $request->input('spec'); // 规格
        $product->logistics_mode = $request->input('logistics_mode'); // 支持的物流方式
        $product->address = $request->input('address');
        $product->cate_id = $request->input('cate_id');
        $product->status = 1;
        $product->save();

        if(!$product){
            return $this->failed('商品创建失败');
        }else {
            return $this->message('商品创建成功');
        }
    }

    /**
     * 商品详情.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = Product::where('shop_id', Auth::guard('shop')->user()->id)->where('id', $id)->first();
        if ($product) {
            return $this->success(new OrderResource($product));
        } else {
            return $this->failed('商品不存在');
        }
    }


    /**
     * 更新商品信息.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $messages = [
            'name.required' => '商品名称不能为空',
            'cover_image.required' => '商品封面不能为空',
            'price.required' => '商品价格不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'cover_image' => 'required',
            'price' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $product = Product::where('shop_id', Auth::guard('shop')->user()->id)->where('id', $id)->first();
        if (!$product) {
            return $this->failed('不存在该商品');
        }

        $picGroup = $request->input('pic_group', []);
        
        // 处理商品封面图片
        $coverImage = $request->input('cover_image', '');
        if(!$coverImage){
            // 没有上传封面图片的时候从图片组里面获取第一张做封面图片
            $coverImage = $picGroup ? $picGroup[0] : '';
        }

        $product->shop_id = $request->user('shop')->id; // 店铺ID
        $product->name = $request->input('name');
        $product->price = number_format($request->input('price'), 2, '.', '');
        $product->unit = $request->input('unit');
        $product->info = $request->input('info');
        $product->description = $request->input('desc');
        $product->cover_image = $coverImage;
        $product->pic_group = $picGroup; // 图片组存为json格式数据
        $product->spec = $request->input('spec'); // 规格
        $product->logistics_mode = $request->input('logistics_mode'); // 支持的物流方式
        $product->address = $request->input('address');
        $product->cate_id = $request->input('cate_id');
        $product->status = 1;
        $product->save();

        return $this->message('商品更新成功');
    }

    /**
     * 删除商品.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product = Product::where('shop_id', $request->user('shop')->id)->where('id', $id)->find();
        if ($product->delete()) {
            return $this->message('删除成功');
        } else {
            return $this->failed('删除失败');
        }
    }

    /**
     * 批量删除商品.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroyBatch(Request $request)
    {
        $ids = $request->input('ids', []);
        $count = 0;
    
        if (!is_array($ids) || count($ids) < 1) {
            return $this->failed('请选择商品');
        }

        $productOrm = Product::where('shop_id', $request->user('shop')->id);
        foreach ($productOrm->whereIn('id', $ids)->get() as $model) {
            if ($model->delete()) {
                $count++;
            }
        }
        return $this->message(sprintf('删除成功%s条数据',  $count));
    }

    /**
     * 上下架
     */
    public function toggleStatus(Request $request, $id)
    {
        $product = Product::where('shop_id', $request->user('shop')->id)->where('id', $id)->first();

        if (!$product) {
            return $this->failed('商品不存在');
        }

        if ($product->status === 1) {
            $product->status = 0;
            $msg = '下架成功';
        } else {
            $product->status = 1;
            $msg = '上架成功';
        }

        $product->save();

        return $this->message($msg);
    }

    /**
     * 图片上传
     *
     * @param Request $request
     * @param ImageUploadHandler $uploader
     * @return void
     */
    public function imageUpload(Request $request, ImageUploadHandler $uploader)
    {
        $fileName = 'cover-img';
        if ($request->hasFile($fileName)) {
            $result = $uploader->save($request->file($fileName), '', $request->user('shop')->id, 750);
            if ($result) {
                return $this->success($result);
            } else {
                return $this->failed('上传失败');
            }
        } else {
            return $this->failed('没有上传文件');
        }
    }
}
